import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
import Layout from "@/layout";
import { getLocalStorage } from "@/utils/index.js";

Vue.use(VueRouter);
/**
 * 重写路由的push方法
 */
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error);
};


const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/components/Login/index.vue")
  },
  {
    path: '/',
    name: 'app',
    component: Layout,
    redirect:'/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Home/index.vue'),
        meta: { title: 'Home', icon: 'home', affix: true }
      }
    ]
  },
  {
    path: '/project',
    name: 'Project',
    component: Layout,
    redirect:'/project/index',
    children: [
      {
        path: '/project/index', // 项目管理
        name: 'ProjectIndex',
        component: () => import('@/views/Project/index.vue'),
        meta: { title: '修改密码', icon: 'dashboard', affix: true }
      },{
        path: '/project/list1', // 项目管理
        name: 'Projectlist1',
        component: () => import('@/views/Project/list1.vue'),
        meta: { title: '操作员管理', icon: 'dashboard', affix: true }
      },
      {
        path: '/project/list2', // 项目管理
        name: 'Projectlist2',
        component: () => import('@/views/Project/list2.vue'),
        meta: { title: '装维员管理', icon: 'dashboard', affix: true }
      }
    ]
  },
  {
    path: "*", // 404
    name: "notfount",
    component: () => import('@/components/404'),
    meta: { title: '404', icon: '404', affix: true }
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});
//路由拦截
let newRoutes = null;
router.beforeEach((to, from, next) => {
  console.log(to.path)
  //判断是否有 已经登录了
  let userInfo = JSON.parse(getLocalStorage("userInfo"));
  if (userInfo) {
    // if (to.path != "/login") {
    //   const hasUser = store.state.userInfo.token?true:false;
    //   console.log(hasUser)
    //   // 刷新动态路由丢失 重新添加载路由
    //   if (!hasUser) {
    //     store.dispatch("ADD_USER_INFO", userInfo);
    //     const routeObj = {
    //       path: "index/test", // 这里要把父路由的路径也带上
    //       name: "test",
    //       meta: { title: "测试路由test", noCache: true },
    //       component: () => import("@/views/Home/index.vue")
    //     };
    //     console.log(router);
    //     next({ ...to, replace: true })
    //   } else {
    //     next()
    //   }
    // }else{
      next();
    // }
  } else {
    if(to.path=="/login"){
      next()
    }else{
      next("/login");
    }
  }
});
export default router;
